<!--
 * @Author: 瞿旺兴 18774621495@163.com
 * @Date: 2022-05-31 15:14:25
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @LastEditTime: 2022-06-08 17:47:23
 * @FilePath: \nien-vue3-admin\src\views\BusinessConfiguration\sellPriceManagement\components\NationalPart.vue
 * @Description: 国家分区
-->
<template>
  <div class="edit-box">
    <inp-val-format v-model:formatValue="batchValue"></inp-val-format>
    <el-button type="primary" :icon="CirclePlus" @click="batchAdd">批量新增</el-button>
    <el-button type="primary" :icon="EditPen" @click="batchEdit">批量修改</el-button>
    <p class="edit-tips">注: 只能修改分区名称和国家2列，国家请输入中文！其他数据会在保存后更新</p>
  </div>
  <div class="btns-box">
    <el-button type="primary" :icon="CirclePlus" @click="addData">新增</el-button>
    <el-button
      type="danger"
      :icon="Delete"
      :loading="deleteMoreLoading"
      :disabled="!selectionList.length"
      @click="deleteMore"
    >
      批量删除
    </el-button>
  </div>
  <el-table
    v-loading="tableLoading"
    :data="tableData"
    max-height="400px"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" align="center"></el-table-column>
    <el-table-column label="分区名称" prop="name"></el-table-column>
    <el-table-column label="国家代码" prop="countryCode"></el-table-column>
    <el-table-column label="方案类型" prop="planTypeId" :formatter="playTypeFormatter"></el-table-column>
    <el-table-column label="国家中文名称" prop="countryName"></el-table-column>
    <el-table-column label="国家英文名称" prop="countryNameEn"></el-table-column>
    <el-table-column label="操作" width="200">
      <template #default="{row}">
        <el-button text type="primary" @click="edit(row)">修改</el-button>
        <el-divider direction="vertical" class="divider-margin" />
        <el-button
          text
          type="primary"
          :loading="!!row.loading"
          @click="handleDelete(row)"
        >
          删除
        </el-button>
        <el-divider direction="vertical" class="divider-margin" />
        <el-button text type="primary" @click="emialSet(row)">设置邮编</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分区修改 -->
  <el-dialog v-model="editVisible" title="修改" width="420px">
    <el-form ref="editFormRef" :model="editData" label-position="top">
      <el-form-item
        label="分区名称" 
        :rules="[{required: true, message: '请输入分区名称', trigger: 'blur'}]"
        prop="name"
      >
        <el-input v-model="editData.name" type="text"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="info" @click="editVisible = false">取消</el-button>
      <el-button type="primary" :loading="editLoading" @click="savePart">保存</el-button>
    </template>
  </el-dialog>
  <email-partition ref="emailPartitionef" />
  <add-contry-partition ref="addContryPartitionRef" :product-id="props.basicInfo.id" @success="addSuccess" />
</template>
<script setup lang="ts" >
import { ref, defineProps, h, watchEffect, reactive } from 'vue'
import { EditPen, CirclePlus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import InpValFormat from './InpValFormat.vue'
import EmailPartition from './EmailPartition.vue'
import AddContryPartition from './AddContryPartition.vue'
import { countryPartitionList, countryPartitionEdit, countryPartitionRemove, batchAddOrUpdate, batchCheckCountry } from '@/api/BusinessConfig/sellPriceManagement'

import { uuid } from '@/utils/index'
import useDicts, { DictDirection } from '@/store/modules/dicts'

const dicts = useDicts()
dicts.setDicts(DictDirection.方案类型)

const props = defineProps({
  basicInfo: {
    type: Object,
    default: () => ({}),
  },
})
const tableLoading = ref(false)
const editVisible = ref<boolean>(false)
const tableData = ref([{}])
const selectionList = ref([])

// 邮编
const emailPartitionef = ref()
const emialSet = (row) => {
  emailPartitionef.value.open(row.id)
}
// 新增
const addContryPartitionRef = ref()

const addData = () => {
  addContryPartitionRef.value.countryOpen = true
}
// 新增成功
const addSuccess = () => {
  getList()
}

// 分区修改
const editData = reactive({ name: '' })
const editLoading = ref<boolean>(false)
const editFormRef = ref()
const edit = (row) => {
  delete row.loading
  Object.assign(editData, { name: '', ...JSON.parse(JSON.stringify(row)) })
  editVisible.value = true
}
const savePart = () => {
  editFormRef.value.validate((value) => {
    if (value) {
      editLoading.value = true
      countryPartitionEdit(editData).then(res => {
        if (res.code === 200) {
          ElMessage.success('修改成功！')
          getList()
        } else {
          ElMessage.success('修改失败！')
        }
      }).finally(() => {
        editVisible.value = false
        editLoading.value = false
      })
    }
  })
}
const handleDelete = (row) => {
  row.loading = true
  deletePart(row.id).then(({ code }) => {
    if (code === 200) {
      ElMessage.success('删除成功！')
    }
  }).finally(() => {
    row.loading = false
  })
}

const deletePart = (ids) => new Promise(resove => {
  ElMessageBox.confirm('是否确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    countryPartitionRemove(ids).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      }
    }).finally(() => {
      resove(true)
    })
  })
})

const deleteMoreLoading = ref<boolean>(false)
const deleteMore = () => {
  const ids = selectionList.value.map(i => i.id).join(',')
  deleteMoreLoading.value = true
  deletePart(ids).then(() => {
    deleteMoreLoading.value = false
  })
}

const handleSelectionChange = (list) => {
  selectionList.value = list
}

const getList = () => {
  if (!props.basicInfo.id) return
  tableLoading.value = true
  countryPartitionList({
    salesProductPriceId: props.basicInfo.id,
    pageSize: 0,
    pageNum: 0,
  }).then(res => {
    if (res.code === 200) {
      tableData.value = res.data || []
    }
  }).finally(() => {
    tableLoading.value = false
  })
}
// 方案类型过滤
const playTypeFormatter = (row) => {
  const obj = dicts[DictDirection.方案类型].find(item => item.dictValue === row.planTypeId)

  return obj && obj.dictLabel
}
// 批量操作
interface batchCheck {
      name: string;
      countryName: string;
      planTypeId?: '1';
      salesProductPriceId?: string;
      uuid?:string;
      id?:number;
}
const batchValue = ref<any[]>([])
const batchAddLoading = ref<boolean>(false)
// 批量操作判断数据是否为空
const isBatchValueEmpty = () => {
  if (!batchValue.value.length) {
    ElMessage.error('请输入数据！')
    return true
  }
  return false
}

// 检测国家是否重复并修改列表数据
const editProptyList = ['name', 'countryCode', 'countryNameEn', 'countryName']
const checkCountry = (params:batchCheck[], flag:boolean) => {
  batchAddLoading.value = true
  batchCheckCountry(params).then(({ code, data }) => {
    if (code !== 200) return 

    const { invalidCountryList, validCountryList } = data
    if (invalidCountryList && invalidCountryList.length !== 0) {
      const invalidStr = invalidCountryList.map(i => i.countryName).join('，')

      ElMessageBox.alert(`国家名：【${ invalidStr }】无效`)
    }

    /* 是否新增 如果有效国家长度大于0，则把有效国家添加入列表 */
    if (flag) {
      if (validCountryList.length !== 0) {
        tableData.value.push(...validCountryList)
      }
    } else {
      if (validCountryList.length === 0) return
      tableData.value.forEach(source => {
        validCountryList.forEach(country => {
          if (source.id == country.id) {
            editProptyList.forEach(key => {
              source[key] = country[key]
            })
          }
        })
      })
    }
    ElMessage.success('操作成功，如需保存请点击保存按钮')
  }).finally(() => {
    batchAddLoading.value = false
  })
}
// 检测重复
const isRepeat = () => {
  const countMap = {}
  batchValue.value.forEach(item => {
    if (countMap[item[1]] === undefined) {
      countMap[item[1]] = 1
    } else {
      countMap[item[1]]++
    }
  })
  const repeatData = Object.entries(countMap).filter(i => i[1] > 1)
  if (repeatData.length) {
    ElMessageBox({
      title: '温馨提示',
      message: h('div', null, [
        h('h3', null, '国家重复了'),
        ...repeatData.map(i => h('p', null, `${ i[0] }:${ i[1] }`)),
      ]),
      confirmButtonText: '确定',
    })
  }
}

// 新增
const batchAdd = () => {
  if (isBatchValueEmpty()) return
  // 判断重复
  isRepeat()
  const curUuid = uuid()
  const params:batchCheck[] = batchValue.value.map(item => ({
    name: item[0],
    countryName: item[1],
    planTypeId: '1',
    salesProductPriceId: props.basicInfo.id,
    uuid: curUuid,
  }))
  checkCountry(params, true)
}
// 修改
const batchEdit = () => {
  if (isBatchValueEmpty()) return
  isRepeat()

  if (batchValue.value.length > tableData.value.length) {
    // 超出处理
    batchValue.value.length = tableData.value.length
  }
  const params:batchCheck[] = batchValue.value.map((item, index) => ({
    name: item[0],
    countryName: item[1],
    id: tableData.value[index].id,
  }))
  checkCountry(params, false)
}

// 初始化
watchEffect(getList)

// 保存
const save = () => batchAddOrUpdate(tableData.value).then(({ code, msg }) => {
  if (code === 200) {
    ElMessage.success(msg)
    getList()
  }
})

defineExpose({
  save,
})
</script>

<style lang="less" scoped>
.edit-box{
    margin-bottom: 16px;
   /deep/.el-textarea{
     width: 540px;
     margin-right: 20px;
   }
   .edit-tips{
      font-family: PingFangSC-Regular;
      font-size: 12px;
      color: #7A8298;
      line-height: 16px;
      margin: 4px 0 0;
   }
}
.btns-box{
  margin-bottom: 12px;
}
.divider-margin{
  margin: 0;
}

</style>